import {createSlice,Dispatch} from '@reduxjs/toolkit'
import {LoginType} from '@/types/User'
import {loginApi} from '@/api/login'
import {getStorage, setStorage} from '@/utils/storeutil'
import {TOKEKEY,USERKEY} from '@/utils/constant'
import {LoginStatusEnum} from '@/types/RabbitEnum'
const userSlice=createSlice({
    name:'userNS',
    initialState:{
       token:getStorage(TOKEKEY)||'',
       user:getStorage(USERKEY)||{}
    },
    reducers:{
        SET_TOKEN(state,action){
            state.token=action.payload
            setStorage(TOKEKEY,action.payload)
        },
        SET_USER(state,action){
            state.user=action.payload
            setStorage(USERKEY,action.payload)
        }
    }
})
export const loginAsync=(payload:LoginType)=>{
    return async(dispatch:Dispatch)=>{
        try {
            const result=await loginApi(payload)
            dispatch(SET_TOKEN(result.data.data.token))
            dispatch(SET_USER(result.data.data.user))
            return LoginStatusEnum.SUCCESS
        } catch (error) {
            return LoginStatusEnum.FAILURE
        }
    }
}

export const {SET_TOKEN,SET_USER}=userSlice.actions
export default userSlice.reducer

